/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hashChunk;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author DongVan
 */
public class ProcessTorrent {

    int FRG_FSIZE = 0;

    public File[] splitFile(File source) throws NoSuchAlgorithmException {
//        ArrayList<String> listSHA1 = new ArrayList<>(); //lưu hash code dưỡi dạng mã háo SHA1
        MessageDigest md = MessageDigest.getInstance("SHA1"); //cài đặt SHA1
        FRG_FSIZE = 1024 * 512;//do dai cua 1 chunk
        int noFile = (int) source.length() / FRG_FSIZE;//So luong chunks cua mot file
        if ((int) source.length() % FRG_FSIZE != 0) {
            noFile++;
        }

        File[] fileFragments = new File[noFile]; //mảng lưu file Chunk
        String[] frgfName = new String[noFile]; //mảng lưu tên file Chunk
        try {
            String sourceFName = source.getName(); //lấy tên file bao gồm cả phần mở rộng
            String extFName = sourceFName.substring(sourceFName.lastIndexOf(".") + 1, sourceFName.length());
            long sourceFSize = source.length(); //lấy kích thước file
            FileInputStream fis = new FileInputStream(source); //đọc cái bit của file
            sourceFName = sourceFName.substring(0, sourceFName.lastIndexOf(".")); //lấy tên file ko chưa phần mở rộng

            File folder = new File("share\\local\\" + sourceFName); //tạo folder temp lưu các file Chunk
            if (!folder.exists()) {
                folder.mkdir();
            } else {
            }
            //tạo file torent để download
            BufferedWriter out = new BufferedWriter(new FileWriter("share\\torent\\" + sourceFName + ".torrent"));
            out.write(String.valueOf(noFile));
            out.newLine();
            out.write(extFName);
            out.newLine();
            String line = "";
            for (int i = 1; i <= noFile; i++) {
                frgfName[i - 1] = folder.getPath() + "\\" + sourceFName + "_" + String.valueOf(i) + ".chunk"; //tên từng chunk 1 (gộp cả đường dẫn file)
                fileFragments[i - 1] = new File(frgfName[i - 1]); //tạo ra file chunk
                FileOutputStream fos = new FileOutputStream(fileFragments[i - 1]);
                if (i == noFile) {
                    FRG_FSIZE = (int) (sourceFSize % FRG_FSIZE);
                }
                byte[] data = new byte[FRG_FSIZE];
                int count = fis.read(data); //trả về tổng số lượng byte đc đọc
                md.update(data, 0, count);
                byte[] mdbytes = md.digest();
                StringBuffer sb = new StringBuffer("");
                for (int j = 0; j < mdbytes.length; j++) {
                    sb.append(Integer.toString((mdbytes[j] & 0xff) + 0x100, 16).substring(1));
                }
//                listSHA1.add(sb.toString());
                fos.write(data);
                fos.close();
                String frgFileInfo = new String(frgfName[i - 1] + "," + String.valueOf(FRG_FSIZE));
                line = sourceFName + "_" + String.valueOf(i) + ".chunk" + ";" + sb.toString();
                out.write(line);
                out.newLine();
            }

            out.close();

            //int debug = 1;
        } catch (Exception e) {
            System.out.println("Error in Splitting " + e);
            JOptionPane.showMessageDialog(null, "Error in Splitting File \n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            return null;
        }
        return fileFragments;
    }

    public static String hashCode(File file) throws NoSuchAlgorithmException, FileNotFoundException, IOException {
        StringBuffer sb = new StringBuffer("");
        MessageDigest md = MessageDigest.getInstance("SHA1"); //cài đặt SHA1
        int FRG_FSIZE = 1024 * 512;//do dai cua 1 chunk
        if (FRG_FSIZE > file.length()) {
            FRG_FSIZE = (int) (file.length() % FRG_FSIZE);
        }
        
        FileInputStream fis = new FileInputStream(file); //đọc cái bit của file
        byte[] data = new byte[FRG_FSIZE];
        int count = fis.read(data); //trả về tổng số lượng byte đc đọc
        md.update(data, 0, count);
        byte[] mdbytes = md.digest();
        for (int j = 0; j < mdbytes.length; j++) {
            sb.append(Integer.toString((mdbytes[j] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

    public File mergeFiles(String path, String ext) {
        try {
            File folder = new File(path);
            File[] files = folder.listFiles();
            File outFile = new File("Temp." + ext);
            FileOutputStream fileOS = new FileOutputStream(outFile);
            for (int i = 0; i < files.length; i++) {
                FileInputStream fileIS = new FileInputStream(files[i]);
                byte[] data = new byte[(int) files[i].length()];
                int count = fileIS.read(data);
                fileOS.write(data);
                fileIS.close();
            }
            fileOS.close();
            return outFile;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error in Merge File \n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        return null;
    }
}
